﻿'Imports System.Web.UI.WebControls
'Imports System.Web.UI.WebControls.WebParts
'Imports System.Web.UI.HtmlControls
Imports ADOEntityImportData
Imports System.IO
Imports System.Data

Partial Class Administrator_frmImportDocument
    Inherits Web.UI.BasePage

#Region "Valiable"
    Private Enum chkStatus
        CountUploadFile
        UploadFile
        CanCel
    End Enum

    'Private Const pathDriveOnServer As String = "K:\\"
    Private Const PROGRAM_CODE As String = "M21"
    Private PathFileOnServer As String = ""
    Dim convertDate As clsDateFormat
    Dim clsSessionMenuRight As clsSessionMenuRight = New clsSessionMenuRight
    Dim clsDatabase As clsDatabase
    Dim importDataEntity As ImportDataEntity
    Dim intBeforeItemIndex As Integer
    Dim dsImportData As New DataSet
    Dim clsDataTable As New clsLINQToDataTable
#End Region

    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        btnSearch.Text = Resources.resButton.btnSearch
        btnModify.Text = Resources.resButton.btnModify
        btnDelete.Text = Resources.resButton.btnDelete
        'btnClear.Text = Resources.resButton.btnClear
        'btnPrint.Text = Resources.resButton.btnPrint

        lblMsg.Text = Resources.resMessageAlert.alertEmptyGrid
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            PathFileOnServer = Server.MapPath(System.Configuration.ConfigurationManager.AppSettings("Path_DOC_MANUAL"))

            btnUpload.Attributes.Add("onclick", "NoDoubleSubmit();")
            'btnDelete.Attributes.Add("onclick", "NoDoubleSubmit();")
            If Not IsPostBack Then
                chkIsLogin()
                CreateControlMP()
                setButton(1)
            Else
                dsImportData = Session("dsImportData")
                grdImportList.DataSource = dsImportData.Tables("sUserManual")
                grdImportList.DataBind()
            End If

        Catch ex As Exception
            ScriptManager.RegisterStartupScript(Me, _
                                                            Me.GetType(), _
                                                            "clientScript", _
                                                            "alert('" + ex.Message.Replace("'", "") + "')", _
                                                            True)

        End Try
    End Sub

    Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
        Session("dsImportData") = dsImportData
    End Sub

    Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
        Try

            If chkBeforeSave() Then
                txtFileName.Text = Path.GetFileName(FileUpload1.Value)

                clsSessionMenuRight = Session("ClsMenuRight")

                convertDate = New clsDateFormat

                Dim doc As New KYC_USER_MANUAL
                doc.MANUAL_NAME = txtManualName.Text
                doc.FILE_NAME = txtFileName.Text
                doc.URL = txtUrl.Text
                doc.UPLOAD_BY = clsSessionMenuRight.getUserName
                doc.UPLOAD_DATE = DateTime.Now

                importDataEntity = New ImportDataEntity()
                importDataEntity.AddToKYC_USER_MANUAL(doc)
                importDataEntity.SaveChanges()

                uploadFileToServer(Path.GetFileNameWithoutExtension(txtFileName.Text))
                IsDataBind()
                reset()
                ScriptManager.RegisterStartupScript(Me, _
                                                    Me.GetType(), _
                                                    "clientScript", _
                                                    "alert('อัพโหลดสำเร็จ')", _
                                                    True)
            End If
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(Me, _
                                                Me.GetType(), _
                                                "clientScript", _
                                                "alert('" + ex.InnerException.Message + "')", _
                                                True)
        End Try

    End Sub



#Region "SetForm"

    Sub CreateControlMP()
        Dim page As Label = CType(Master.FindControl("lblPage"), Label)
        page.Text = "จัดการไฟล์เอกสาร > นำเข้าคู่มือการใช้โปรแกรม"

    End Sub

    Private Sub setButton(ByVal button As Integer)

        If button = 1 Then 'unselect
            menu.Enabled = True
            txtManualName.Enabled = True

            btnUpload.Enabled = True
            FileUpload1.Visible = True
            txtFileName.Visible = False

            btnSearch.Enabled = True
            btnModify.Text = "แก้ไข"
            btnModify.Enabled = False
            btnDelete.Enabled = False
        ElseIf button = 2 Then 'select
            menu.Enabled = False
            txtManualName.Enabled = True

            btnUpload.Enabled = False
            FileUpload1.Visible = False

            txtFileName.Visible = True
            'TxtPathFileUpload.Enabled = False

            btnSearch.Enabled = False
            btnModify.Enabled = True
            btnDelete.Enabled = True
        End If
    End Sub

    Private Sub reset()
        clearGvIndex()
        setButton(1)
        'lblMsg.Visible = False
        txtManualName.Text = ""
        txtFileName.Text = ""
        txtUrl.Text = ""
    End Sub

    Private Sub clearGvIndex()
        grdImportList.SelectedIndex = -1
    End Sub

#End Region


#Region " Function "

    Private Sub IsDataBind()
        Try

            importDataEntity = New ImportDataEntity

            If dsImportData.Tables.Contains("sUserManual") Then
                dsImportData.Tables.Clear()
            End If
            Dim qry = From doc In importDataEntity.KYC_USER_MANUAL
                            Order By doc.MANUAL_NAME
                        Select doc.MANUAL_NAME, doc.FILE_NAME, doc.UPLOAD_DATE, doc.URL

            If Not (txtManualName.Text = "") Then
                qry = qry.Where(Function(doc) doc.MANUAL_NAME.Contains(txtManualName.Text))
            End If

            If Not (txtUrl.Text = "") Then
                qry = qry.Where(Function(doc) doc.URL.Contains(txtUrl.Text))
            End If

            dsImportData.Tables.Add(clsDataTable.LINQToDataTable(qry, "sUserManual").Copy)

            If (qry.Count = 0) Then
                lblMsg.Visible = True
                lblTotal.Text = ""
            Else
                lblMsg.Visible = False
                lblTotal.Text = "จำนวนรายการทั้งหมด " + qry.Count.ToString + " รายการ "

            End If

            grdImportList.DataSource = dsImportData.Tables("sUserManual")
            grdImportList.DataBind()

            clsDataTable = Nothing
        Catch ex As Exception
            WriteError(ex, "IsDataBind", "frmImportDocument")

        End Try
    End Sub

    Private Function checkInfoName(ByVal infoName As String) As Boolean
        Dim result As Boolean = True
        importDataEntity = New ImportDataEntity

        Dim count As Integer = (From loginInfo In importDataEntity.KYC_LOGIN_INFO Where loginInfo.INFO_NAME = infoName).Count

        If Not (count = 0) Then
            result = False
        End If

        Return result
    End Function

    Private Function checkFileName(ByVal fileName As String) As Boolean
        Dim result As Boolean = True
        importDataEntity = New ImportDataEntity

        Dim count As Integer = (From loginInfo In importDataEntity.KYC_LOGIN_INFO Where loginInfo.FILE_NAME = fileName).Count

        If Not (count = 0) Then
            result = False
        End If

        Return result
    End Function

    Private Function chkBeforeSave() As Boolean
        Dim result As Boolean = True

        If txtUrl.Text = "" Then
            result = False
            ScriptManager.RegisterStartupScript(Me, _
                                                Me.GetType(), _
                                                "clientScript", _
                                                "alert('กรุณาเลือกเมนู')", _
                                                True)
        ElseIf FileUpload1.PostedFile.ContentLength = 0 Then
            result = False
            ScriptManager.RegisterStartupScript(Me, _
                                                Me.GetType(), _
                                                "clientScript", _
                                                "alert('กรุณาเลือกไฟล์ที่ต้องการอัพโหลด')", _
                                                True)
        ElseIf checkFileUploadType() Then
            result = False
            ScriptManager.RegisterStartupScript(Me, _
                                                Me.GetType(), _
                                                "clientScript", _
                                                "alert('กรุณาอัพโหลดเฉพาะไฟล์ PDF เท่านั้น')", _
                                                True)
        ElseIf FileUpload1.PostedFile.ContentLength > 10240000 Then
            result = False
            ScriptManager.RegisterStartupScript(Me, _
                                                Me.GetType(), _
                                                "clientScript", _
                                                "alert('ขนาดไฟล์ไม่ควรเกิน 10 MB')", _
                                                True)

        ElseIf txtManualName.Text = "" Then
            result = False
            ScriptManager.RegisterStartupScript(Me, _
                                                Me.GetType(), _
                                                "clientScript", _
                                                "alert('กรุณาระบุชื่อคู่มือการใช้งาน')", _
                                                True)
        End If

        Return result
    End Function

    Private Function checkFileUploadType() As Boolean
        Dim ret As Boolean = True
        Dim fileType As String = FileUpload1.PostedFile.ContentType.Split(New Char() {"/"})(1)

        If fileType = "pdf" Then
            ret = False
        End If

        Return ret

    End Function

    Private Sub uploadFileToServer(ByVal strFileName As String)
        Try
            Dim fn As String = ""
            Dim fnBackup As String = ""
            Dim strPathBatch As String = ""

            If (FileUpload1.Visible = True) Then
                txtFileName.Text = FileUpload1.Value
            End If


            Dim strFileNameToSplit As String = txtFileName.Text
            Dim arrString As String() = strFileNameToSplit.Split(".")
            fn = strFileName.Trim & "." & arrString(arrString.Length - 1)

            Dim savePath As String = Path.Combine(PathFileOnServer, fn)

            If (FileUpload1.Visible = True) Then
                FileUpload1.PostedFile.SaveAs(savePath)
            Else
                If File.Exists(savePath) = True Then
                    DeleteFile(savePath)
                End If
            End If

        Catch ex As Exception
            WriteError(ex, "uploadFileToServer", "frmImportDocument")
            Throw New Exception("เกิดข้อผิดพลาดในการอัพโหลดไฟล์")
        End Try

    End Sub

    Private Function FileExists(ByVal FileFullPath As String) As Boolean
        Try
            Dim f As New IO.FileInfo(FileFullPath)
            Return f.Exists
        Catch ex As Exception
            WriteError(ex, "FileExists", "frmImportDocument")

            Throw New Exception("เกิดข้อผิดพลาด FileExists ")
        End Try
    End Function

    Private Function DeleteFileInDirectory(ByVal targetDirectory As String) As Boolean
        Dim blnSuccess As Boolean = False
        Dim strTest As String = ""

        Try
            strTest = 1
            Dim fileEntries As String() = Directory.GetFiles(targetDirectory)
            strTest = 2
            ' Process the list of files found in the directory.
            Dim fileName As String

            For Each fileName In fileEntries
                strTest = 3
                File.Delete(fileName)
            Next fileName
            strTest = 4
            blnSuccess = True
        Catch ex As Exception
            WriteError(ex, "DeleteFileInDirectory", "frmImportDocument")
            Throw New Exception("เกิดข้อผิดพลาด DeleteFileInDirectory " & strTest)
        End Try
        Return blnSuccess
    End Function

    Private Function DeleteFile(ByVal FileName As String) As Boolean
        Dim blnSuccess As Boolean = False
        Try
            File.Delete(FileName)
            blnSuccess = True
        Catch ex As Exception
            WriteError(ex, "DeleteFile", "frmImportDocument")
            Throw New Exception("เกิดข้อผิดพลาด DeleteFile ")
        End Try
        Return blnSuccess
    End Function

#End Region



    Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        If dsImportData.Tables.Contains("sUserManual") Then
            dsImportData.Tables("sUserManual").Clear()
            grdImportList.DataSource = dsImportData.Tables("sUserManual")
            grdImportList.DataBind()
        End If

        reset()
        clearGvIndex()
        setButton(1)
        lblMsg.Visible = False
        lblTotal.Text = ""
    End Sub

    Private Sub SaveLog(ByVal index As Integer)
        Try
            Dim program As String = PROGRAM_CODE
            Dim programName As String = " จัดการไฟล์เอกสาร > นำเข้าคู่มือการใช้โปรแกรม"

            Dim desc As String = ""

            If index = 2 Then
                If Not txtUrl.Text = "" Then
                    desc += " Url - " + txtUrl.Text
                End If
                If Not txtManualName.Text = "" Then
                    desc += " ชื่อคู่มือการใช้งาน - " + txtManualName.Text
                End If
                desc = "ค้นหา" + programName + " (" + desc + ")"
            ElseIf index = 3 Then
                desc = "บันทึก" + programName + " (นำเข้าข้อมูล " + txtFileName.Text + ")"
            ElseIf index = 4 Then
                desc = "แก้ไข" + programName + " (นำเข้าข้อมูล " + txtFileName.Text + ")"
            ElseIf index = 5 Then
                desc = "ลบ" + programName + " (นำเข้าข้อมูล " + txtFileName.Text + ")"
            End If

            Dim clsLogTransaction As New clsLogTransaction
            clsLogTransaction.saveLogTransaction("", clsSessionMenuRight.getUserName, index, desc, program)


            clsLogTransaction = Nothing
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Protected Sub grdImportList_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles grdImportList.PageIndexChanging
        grdImportList.PageIndex = e.NewPageIndex
        clearGvIndex()
        DataBind()
    End Sub

    Protected Sub grdImportList_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdImportList.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            Dim link As HyperLink = e.Row.FindControl("linkImg")
            Dim doc As DataRowView = e.Row.DataItem

            link.NavigateUrl = System.IO.Path.Combine(System.Configuration.ConfigurationManager.AppSettings("Path_DOC_MANUAL"), doc("file_name").ToString)
        End If
    End Sub

    Protected Sub grdImportList_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles grdImportList.SelectedIndexChanged
        If (grdImportList.SelectedIndex = intBeforeItemIndex) Then
            clearGvIndex()
            reset()

            btnModify.Text = "แก้ไข"
        Else
            btnModify.Text = "บันทึก"

            setButton(2)


            'Dim row As DataRow = dsImportData.Tables("sUserManual").Rows(grdImportList.Rows(grdImportList.SelectedIndex))
            txtManualName.Text = grdImportList.Rows(grdImportList.SelectedIndex).Cells(1).Text
            txtFileName.Text = CType(grdImportList.Rows(grdImportList.SelectedIndex).Cells(2).FindControl("linkImg"), HyperLink).Text
            txtUrl.Text = grdImportList.Rows(grdImportList.SelectedIndex).Cells(3).Text

            btnDelete.Attributes.Add("onclick", "return confirm('" + String.Format(Resources.resValidate.confirmDelete, _
                       IIf(grdImportList.SelectedIndex = -1, "", grdImportList.Rows(grdImportList.SelectedIndex).Cells(1).Text)) + "');")
        End If
    End Sub

    Protected Sub grdImportList_SelectedIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSelectEventArgs) Handles grdImportList.SelectedIndexChanging
        intBeforeItemIndex = grdImportList.SelectedIndex
    End Sub

    Protected Sub btnModify_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnModify.Click
        Try
            'Save Edit
            importDataEntity = New ImportDataEntity
            Dim url = txtUrl.Text
            convertDate = New clsDateFormat
            Dim qry = (From doc In importDataEntity.KYC_USER_MANUAL Where doc.URL = url).ToList

            If qry.Count > 0 Then
                qry(0).MANUAL_NAME = txtManualName.Text
                qry(0).FILE_NAME = txtFileName.Text
                qry(0).URL = txtUrl.Text

                importDataEntity.SaveChanges()
            End If

            SaveLog(4)

            IsDataBind()
            reset()

            ScriptManager.RegisterStartupScript(Me, _
                                                Me.GetType(), _
                                                "clientScript", _
                                                "alert('" + Resources.resMsgKYC.msgSave + "')", _
                                                True)

        Catch ex As System.Data.UpdateException
            ScriptManager.RegisterStartupScript(Me, _
                                                    Me.GetType(), _
                                                    "clientScript", _
                                                    "alert('" + ex.InnerException.Message + "')", _
                                                    True)
            WriteError(ex, "btnModify_Click", "frmImportDocument")
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(Me, Me.GetType(), "clientScript", "alert('บันทึกผิดพลาด')", True)
            WriteError(ex, "btnModify_Click", "frmImportDocument")
        End Try
    End Sub

    Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        If Not (grdImportList.SelectedIndex = -1) Then
            Dim url As String = grdImportList.Rows(grdImportList.SelectedIndex).Cells(3).Text

            Try
                importDataEntity = New ImportDataEntity

                Dim qry = (From doc In importDataEntity.KYC_USER_MANUAL Where doc.URL = url).ToList

                If qry.Count > 0 Then
                    importDataEntity.DeleteObject(qry(0))

                    importDataEntity.SaveChanges()

                    Dim pathFile = Path.Combine(PathFileOnServer, qry(0).FILE_NAME)
                    DeleteFile(pathFile)
                End If

                SaveLog(5)

                IsDataBind()
                reset()

            Catch ex As System.Data.UpdateException
                Dim codeError() As String = ex.InnerException.Message.Split(":")
                If codeError(0) = "ORA-02292" Then
                    ScriptManager.RegisterStartupScript(Me, Me.GetType(), "clientScript", "alert('ไม่สามารถลบได้ เนื่องจากมีการนำมาใช้ในระบบแล้ว')", True)
                Else
                    ScriptManager.RegisterStartupScript(Me, Me.GetType(), "clientScript", "alert('" + ex.InnerException.Message + "')", True)
                End If
                WriteError(ex, "btnDelete_Click", "frmImportDocument")
            Catch ex As Exception
                ScriptManager.RegisterStartupScript(Me, Me.GetType(), "clientScript", "alert('" + Resources.resError.errorMessage + "')", True)
                WriteError(ex, "btnDelete_Click", "frmImportDocument")
            End Try
        Else
            ScriptManager.RegisterStartupScript(Me, Me.GetType(), "clientScript", "alert('" + Resources.resValidate.nonSelectGridDelete + "')", True)

        End If
    End Sub

    Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
        IsDataBind()
        clearGvIndex()
        SaveLog(2)
    End Sub

    Protected Sub grdImportList_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles grdImportList.Sorting
        Dim dt = TryCast(dsImportData.Tables("sUserManual"), DataTable)

        If dt IsNot Nothing Then

            'Sort the data.
            dt.DefaultView.Sort = e.SortExpression & " " & GetSortDirection(e.SortExpression)
            grdImportList.DataSource = dsImportData.Tables("sUserManual")
            grdImportList.DataBind()
            clearGvIndex()
        End If
    End Sub

    Private Function GetSortDirection(ByVal column As String) As String

        ' By default, set the sort direction to ascending.
        Dim sortDirection = "DESC"

        ' Retrieve the last column that was sorted.
        Dim sortExpression = TryCast(ViewState("SortExpression"), String)

        If sortExpression IsNot Nothing Then
            ' Check if the same column is being sorted.
            ' Otherwise, the default value can be returned.
            If sortExpression = column Then
                Dim lastDirection = TryCast(ViewState("SortDirection"), String)
                If lastDirection IsNot Nothing _
                  AndAlso lastDirection = "DESC" Then

                    sortDirection = "ASC"

                End If
            End If
        End If

        ' Save new values in ViewState.
        ViewState("SortDirection") = sortDirection
        ViewState("SortExpression") = column
        Return sortDirection
    End Function

    Protected Sub menu_MenuItemClick(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.MenuEventArgs) Handles menu.MenuItemClick
        txtUrl.Text = e.Item.Value
    End Sub
End Class
